package com.sk.weichat.ui.contacts;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.NewFriendAdapter;
import com.sk.weichat.bean.AddAttentionResult;
import com.sk.weichat.bean.AttentionUser;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.FriendHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.nearby.UserListGatherActivity;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.sk.weichat.xmpp.listener.NewFriendListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import okhttp3.Call;

/**
 * 新的好友
 */
public class NewFriendActivity extends BaseActivity implements NewFriendListener {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView mPullToRefreshListView;
    private NewFriendAdapter mAdapter;
    private List<NewFriendMessage> mNewFriends;
    private String mLoginUserId;
    private LinearLayout linearEmpty;
    private TextView tvSearchFriend;
    private Handler mHandler = new Handler();
    private ImageView mImgRight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_pullrefresh_list);
        mLoginUserId = coreManager.getSelf().getUserId();
        mNewFriends = new ArrayList<>();
        initActionBar();
        initView();
        ListenerManager.getInstance().addNewFriendListener(this);

        FriendDao.getInstance().markUserMessageRead(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE);
        // 将所有消息都变为已读
        NewFriendDao.getInstance().markNewFriendRead(mLoginUserId);

        NewFriendDao.getInstance().resetAllNewFriendUnRead(mLoginUserId);
    }

    private void initActionBar() {
        getSupportActionBar().hide();

        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText("关系通知");

        mImgRight = (ImageView) findViewById(R.id.iv_title_right);
        mImgRight.setImageResource(R.drawable.icon_clear_big);

        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mImgRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showClearUnReadDialog();

            }
        });

    }

    /**
     * 清除关系通知弹框
     */
    private void showClearUnReadDialog() {

        SelectionFrame mSF = new SelectionFrame(this);
        mSF.setSomething(getString(R.string.dialog_title), getString(R.string.msg_clear_relation), new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {

            }

            @Override
            public void confirmClick() {
                NewFriendDao.getInstance().removeAllNewFriendMsg(mLoginUserId);
                mNewFriends.clear();
                mAdapter.notifyDataSetChanged();
                linearEmpty.setVisibility(View.VISIBLE);
                mImgRight.setVisibility(View.GONE);
                MsgBroadcast.broadcastMsgUiUpdate(getApplicationContext());
            }
        });
        mSF.show();
    }

    protected void onDestroy() {
        super.onDestroy();
        ListenerManager.getInstance().removeNewFriendListener(this);
    }

    private void initView() {
        linearEmpty = findViewById(R.id.linear_empty_tips);
        tvSearchFriend = findViewById(R.id.tv_search_friend);
        tvSearchFriend.setText("暂无关系通知");
        tvSearchFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(NewFriendActivity.this, UserListGatherActivity.class));
            }
        });
        mPullToRefreshListView = findViewById(R.id.pull_refresh_list);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mPullToRefreshListView.setLayoutManager(manager);
        mAdapter = new NewFriendAdapter(coreManager.getSelf().getUserId(), mNewFriends);
        mPullToRefreshListView.setAdapter(mAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) mPullToRefreshListView.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //侧滑删除单个item
                if (view.getId()==R.id.delete_tv){
                    NewFriendDao.getInstance().removeNewFriendMsg(mLoginUserId,mNewFriends.get(position).getUserId());
                    mNewFriends.remove(position);

                    if(mNewFriends.size()==0){
                        linearEmpty.setVisibility(View.VISIBLE);
                        mImgRight.setVisibility(View.GONE);
                    }
                    mAdapter.notifyDataSetChanged();
                    MsgBroadcast.broadcastMsgUiUpdate(getApplicationContext());
                }else if (view.getId()==R.id.layout_new_friend_item){
                    Intent intent = new Intent(mContext, PersonalCenterActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, mNewFriends.get(position).getUserId());
                    mContext.startActivity(intent);
                }
            }
        });

        refreshLayout  = findViewById(R.id.refresh_search_layout);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    /**
     * 请求公共消息
     * <p>
     * 是下拉刷新，还是上拉加载
     */
    private void loadData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long startTime = System.currentTimeMillis();
                final List<NewFriendMessage> friends = NewFriendDao.getInstance().getAllNewFriendMsg(mLoginUserId);
                // 保证至少200ms的刷新过程
                long delayTime = 200 - (startTime - System.currentTimeMillis());
                if (delayTime < 0) {
                    delayTime = 0;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mNewFriends.clear();
                        if (friends != null && friends.size() > 0) {
                            mNewFriends.addAll(friends);
                        }
                        if (mNewFriends != null && mNewFriends.size() > 0){
                            linearEmpty.setVisibility(View.GONE);
                        }else {
                            linearEmpty.setVisibility(View.VISIBLE);
                            mImgRight.setVisibility(View.GONE);
                        }
                        mAdapter.notifyDataSetChanged();
                        refreshLayout.finishRefresh();
                    }
                }, delayTime);
            }
        }).start();

    }

    @Override
    public void onNewFriendSendStateChange(String toUserId, NewFriendMessage message, int messageState) {
    }

    @Override
    public boolean onNewFriend(NewFriendMessage message) {
        loadData();
        return true;
    }
}
